<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    /**
     * 分类列表
     */
    public function index(Request $request)
    {
        if($request->input('type') == 'all'){
            return cache_category_all();
        }else{
            return cache_category();
        }
    }

    /**
     * 添加分类
     */
    public function store(Request $request)
    {
        // 检查参数
        $check = $this->checkInput($request);
        if(is_array($check)){return $check;}

        Category::create($check);

        //清空缓存
        //cache_category_forget();

        return $this->response->created();
    }

    /**
     * 分类详情
     */
    public function show(Category $category)
    {
        return $category;
    }

    /**
     * 更新分类
     */
    public function update(Request $request, Category $category)
    {
        $check = $this->checkInput($request);
        if(is_array($check)){return $check;}

        $category::update($check);

        //清空缓存
        //cache_category_forget();

        return $this->response->noContent();
    }

    /**
     * 验证输入数据
     */
    protected function checkInput($request){

        $request->validate([
            'name' => "required|max:16"
        ], [
            'name.required'=>'分类名称不能为空'
        ]);

        $pid = $request->input('pid', 0);
        $level = $pid == 0 ? 1 : (Category::find($pid)->level + 1);
        if($level > 3) return $this->response->errorBadRequest('分类不能超过3级');

        return ['pid'=>$pid, 'level'=>$level];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function status(Category $category)
    {
        $category->status = $category->status == 1 ? 0 : 1;
        $category->save();

        //清空缓存
//        cache_category_forget();

        return $this->response->noContent();
    }
}
